package com.danskin.wechat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.danskin.wechat.api.client.DanskinCRMApiClient;
import com.danskin.wechat.dao.CrmBrandInfoDao;
import com.danskin.wechat.dao.CustInfoDao;
import com.danskin.wechat.dao.CustInfoExDao;
import com.danskin.wechat.dao.CustItemRecordDao;
import com.danskin.wechat.dao.CustItemRecordDetailDao;
import com.danskin.wechat.dao.CustPointRecordDao;
import com.danskin.wechat.dao.ProductInfoDao;
import com.danskin.wechat.dto.CRMMemberRequest;
import com.danskin.wechat.entity.CustInfo;
import com.danskin.wechat.entity.CustInfoEx;
import com.danskin.wechat.entity.CustItemRecord;
import com.danskin.wechat.entity.CustItemRecordDetail;
import com.danskin.wechat.entity.CustPointRecord;
import com.danskin.wechat.entity.ProductInfo;
import com.danskin.wechat.service.CustItemRecordService;
import com.danskin.wechat.service.WechatMsgTemplateService;
import com.danskin.wechat.util.BeanUtil;
import com.danskin.wechat.util.DateUtils;
import com.danskin.wechat.util.Page;
import com.danskin.wechat.util.StringUtil;

@Service
public class CustItemRecordServiceImpl implements CustItemRecordService {
	@Autowired
	private CustItemRecordDao custItemRecordDao;
	@Autowired
	private CustInfoExDao custInfoExDao;
	@Autowired
	private CustItemRecordDetailDao custItemRecordDetailDao;
	@Autowired
	private ProductInfoDao productInfoDao;
	@Autowired
	private CustPointRecordDao custPointRecordDao;
	@Autowired
	private CrmBrandInfoDao crmBrandInfoDao;
	@Autowired
	private CustInfoDao custInfoDao;
	@Autowired
	private WechatMsgTemplateService wechatMsgTemplateService;

	@Override
	public List<CustItemRecord> getCustItemRecordList(Page page) {
		Map<String, Object> map = page.getMap();
		String title = (String) map.get("parameter");
		String newStartTime = (String) map.get("startTime");
		String newTime = (String) map.get("endTime");
		if (StringUtils.isNotEmpty(title)) {
			if (isNumeric(title)) {
				map.put("consigneeMobile", title);
			} else {
				map.put("consigneeName", title);
			}
		}
		if (StringUtils.isNotEmpty(newStartTime)) {
			map.put("newStartTime", newStartTime + " " + "00:00:01");
		}
		if (StringUtils.isNotEmpty(newTime)) {
			map.put("newTime", newTime + " " + "23:59:59");
		}
		return custItemRecordDao.listPageCustItemRecordList(page);
	}
	private boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}
	@Override
	public List<CustItemRecord> findCustItemRecordList(Page page, String openId, String type) {
		// TODO Auto-generated method stub
		String orderStatus = null;
		if (!"".equals(type)) {
			if (type.equals("waitsend")) {
				// 待发货
				orderStatus = "3";
			} else if (type.equals("waitget")) {
				// 待收货
				orderStatus = "4";
			} else if (type.equals("over")) {
				// 已完成
				orderStatus = "5";
			} else if (type.equals("all")) {
				orderStatus = "";
			}
		}
		Map<String, Object> map = page.getMap();
		map.put("openId", openId);
		map.put("orderStatus", orderStatus);
		return custItemRecordDao.listPageSearchFindCustItemRecordList(page);
	}

	@Override
	public CustItemRecord findCustItemRecordModel(String appId, String openId, String id) {
		// TODO Auto-generated method stub
		return custItemRecordDao.findCustItemRecordModel(appId, openId, id);
	}

	@Override
	public int insertCustItemRecord(String openId, String appId, String address, String city, String district,
			String name, String phone, String province, JSONArray dataList, String access_token) {
		CustInfoEx ex = custInfoExDao.queryCustInfoEx(appId, openId);
		if (ex != null) {
			List<Integer> listId = new ArrayList<Integer>();
			if (dataList != null) {
				for (int i = 0; i < dataList.size(); i++) {
					JSONObject job = (JSONObject) dataList.get(i);
					String id = job.get("id").toString();
					listId.add(Integer.parseInt(id));
				}
			}
			List<ProductInfo> listProductInfo = productInfoDao.queryProductInfoByModle(listId);
			CustItemRecord record = new CustItemRecord();
			record.setMpId(ex.getMpId());
			record.setCustExId(ex.getId());
			String orderNo = BeanUtil.createOrderNumber();
			record.setTransDate(BeanUtil.tradeDate());
			record.setOrderNo(orderNo);
			record.setConsigneeName(name);
			record.setConsigneeMobile(phone);
			record.setConsigneeTel("");
			record.setProvince(province);
			record.setCity(city);
			record.setDistrict(district);
			record.setTown("");
			record.setDetailAddress(address);
			if (listProductInfo.get(0).getProdType() == 1) {
				record.setOrderStatus(5);
				record.setFinishedTime(new Date());
			} else {
				record.setOrderStatus(3);
			}
			record.setShipperCode("");
			record.setShippingNo("");
			List<CustItemRecordDetail> listDetail = new ArrayList<CustItemRecordDetail>();
			CustInfo custInfo = custInfoDao.getCustInfoMobile(openId);
			// 保存兑换记录明细
			String brandId = this.queryCrmBrandInfo(ex.getMpId());
			int totalPoints = 0;
			if (dataList != null) {
				Integer totalNum = 0;
				StringBuffer bf = new StringBuffer();
				for (int i = 0; i < dataList.size(); i++) {
					CustItemRecordDetail cd = new CustItemRecordDetail();
					JSONObject job = (JSONObject) dataList.get(i);
					String id = job.get("id").toString();
					String num = job.get("num").toString();
					String weight = job.get("weight").toString();
					int iNum = Integer.parseInt(num);
					ProductInfo info = this.getProdInfoSum(id, listProductInfo);
					bf.append(info.getName() + "、");
					cd.setProductId(Integer.parseInt(id));
					cd.setProductName(this.getProductName(listProductInfo,id));
					cd.setProductQty(iNum);
					cd.setPoints(info.getSalePoints() * iNum);
					cd.setCreatedTime(new Date());
					cd.setWeight(weight);
					listDetail.add(cd);
					// 如果是券
					if (1 == info.getProdType()) {
						CRMMemberRequest r = new CRMMemberRequest();
						r.setMemberId(ex.getMemberId());
						r.setMobile(custInfo.getMobile());
						r.setBrandId(brandId);
						DanskinCRMApiClient.createInstance().pointBuyCoupon(r, info.getCouponTemplateId(), iNum,
								cd.getPoints());
					}
					// 处理库存问题(扣减)
					productInfoDao.updateProductInfoStock(id, num);
					totalNum += iNum;
					totalPoints += cd.getPoints();
				}
				// 积分兑换商品成功通知
				String prodNames = bf.toString();
				wechatMsgTemplateService.sendCustPointGetItemMsg(access_token, appId, openId, custInfo.getName(),
						custInfo.getMobile(), prodNames.substring(0, prodNames.length() - 1), totalNum, totalPoints);
			}

			record.setTotalPoints(totalPoints);
			custItemRecordDao.insertCustItemRecord(record);
			int custItemId = record.getId();
			// 会员兑换记录明细
			for (CustItemRecordDetail cd : listDetail) {
				cd.setCustItemId(custItemId);
			}
			custItemRecordDetailDao.insertCustItemRecordDetail(listDetail);

			// 只有实物才可以扣减微信端的积分数据，Modified by likui.liu @ 2017-11-08
			int prodType = listProductInfo.get(0).getProdType();
			if (prodType == 2) {
				// 计算个人积分及个人积分明细信息
				int avaPoints = ex.getAvaPoints() - totalPoints;
				// 减扣会员积分
				ex.setAvaPoints(avaPoints);
				custInfoExDao.updateCustInfoExAvaPoints(ex);
				// 插入cust_point_record表数据
				CustPointRecord custPointRecord = new CustPointRecord();
				custPointRecord.setCustExId(ex.getId());
				Integer point = Integer.parseInt("-" + totalPoints);
				custPointRecord.setPoints(point);
				custPointRecord.setSource("积分商城购物");
				custPointRecord.setGetTime(new Date());
				custPointRecord.setExpiredTime(DateUtils.getNextYear());
				custPointRecord.setMemberId(ex.getMemberId());
				custPointRecord.setAvaPoints(0);
				custPointRecord.setTotalPoints(0);
				custPointRecord.setChangeId(StringUtil.getShortUUID());
				custPointRecord.setBrandId(Integer.parseInt(brandId));
				custPointRecord.setCreatedTime(new Date());
				custPointRecordDao.insertCustPointRecord(custPointRecord);
				// 积分变动通知
				wechatMsgTemplateService.sendCustChangePointsMsg(access_token, appId, openId, custInfo.getName(),
						custInfo.getMobile(), point, avaPoints);

				// 调用crm接扣通知积分，这个crm会推送数据
				DanskinCRMApiClient.createInstance().sendPointToCRM(custPointRecord.getChangeId(), ex.getMemberId(),
						custInfo.getMobile(), point, "积分商城购物", brandId);
			}
			return custItemId;
		}
		return -1;
	}
    public String getProductName(List<ProductInfo> listProductInfo,String id){
    	String name="";
    	if(listProductInfo.size()>0){
    		for(ProductInfo info:listProductInfo){
    			String pId =  String.valueOf(info.getId());
    			if(pId.equals(id)){
    				name = info.getName();
    				break;
    			}
    		}
    	}
    	return name;
    }
	public String queryCrmBrandInfo(int mpId) {
		return crmBrandInfoDao.queryCrmBrandInfo(mpId);
	}

	private ProductInfo getProdInfoSum(String prodInfoId, List<ProductInfo> listProductInfo) {
		// ProductInfo productInfo = new ProductInfo();
		if (listProductInfo.size() > 0) {
			for (ProductInfo fo : listProductInfo) {
				String pid = String.valueOf(fo.getId());
				if (prodInfoId.equals(pid)) {
					return fo;
				}
			}
		}
		return null;
	}

	/**
	 * 获取总积分
	 * 
	 * @param num
	 * @param salePoints
	 * @return
	 */
	// private int getTotalPoints(JSONArray dataLsit, List<ProductInfo>
	// listProductInfo) {
	// int sunPoints = 0;// 订单总积分
	// if (dataLsit != null) {
	// for (int i = 0; i < dataLsit.size(); i++) {
	// JSONObject job = (JSONObject) dataLsit.get(i);
	// String id = job.get("id").toString();
	// String num = job.get("num").toString();
	// ProductInfo info = this.getProdInfoSum(id, listProductInfo);
	// int salePoints = 0;
	// if (info != null) {
	// salePoints = info.getSalePoints();// 销售积分
	// }
	// sunPoints += salePoints * Integer.parseInt(num);
	// }
	// }
	// return sunPoints;
	// }

	@Override
	public CustItemRecord findCustItemRecordById(String id) {
		// TODO Auto-generated method stub
		return custItemRecordDao.findCustItemRecordById(id);
	}

	@Override
	public int updateCustItemRecord(CustItemRecord custItemRecord) {
		// TODO Auto-generated method stub
		return custItemRecordDao.updateCustItemRecord(custItemRecord);
	}

	@Override
	public void updateCustItemRecordOrderStatus(String id) {
		// TODO Auto-generated method stub
		custItemRecordDao.updateCustItemRecordOrderStatus(id);
	}

	@Override
	public List<CustItemRecord> queryCustItemRecord(Page page) {
		// TODO Auto-generated method stub
		return custItemRecordDao.listPageQueryCustItemRecord(page);
	}

	@Override
	public List<CustItemRecord> getCustItemRecordExport(String orderNo, String mobile, String name, String startTime,
			String endTime, String mpId) {
		if (StringUtils.isNotEmpty(startTime)) {
			startTime = startTime + " " + "00:00:01";
		}else{
			startTime = DateUtils.getStartTime() + " " + "00:00:01";
		}
		if (StringUtils.isNotEmpty(endTime)) {
			endTime = endTime + " " + "23:59:59";
		}else{
			endTime = DateUtils.getEndTime() + " " + "23:59:59";
		}
		return custItemRecordDao.getCustItemRecordExport(orderNo,mobile,name,startTime,endTime,mpId);
	}
}
